//-----------------------------------------------------------------------
// <copyright file="DisconnectUsers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author></author>
// <email></email>
// <date>2004-03-23</date>
// <summary>Disconnects all Sql User processes that may be running.</summary>
//-----------------------------------------------------------------------

namespace Microsoft.Sdc.Tasks.Sql
{
    using System;
    using System.Xml;
    using System.Globalization;
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
    using SdcSql = Microsoft.Sdc.Tasks.Configuration.SqlServer;
    using Microsoft.Build.Framework;


    /// <summary>
    /// Kill all processes acting on the specified table
    /// </summary>
    /// <remarks>
    /// <code><![CDATA[<Sql.DisconnectUsers (ServerName="serverName" connectionTimeout="timeout" | ConnectionString="connection") DatabaseName="database" commandTimeout="timeout" />]]></code>
    /// <para>where:</para>
    /// <para><i>databaseName (Required)</i></para>
    /// <para>The database on the specified server to grant access to.</para>
    /// <para><i>ConnectionString</i></para>
    /// <para>A valid connection string used to connect the SQL server to run the operation on.</para>
    /// <para><i>ServerName</i></para>
    /// <para>The server to disconnect users from (used instead of <see cref="SqlBase.ConnectionString"/>)</para>
    /// <para><i>ConnectionTimeout</i></para>
    /// <para>Number of seconds to wait before failing a connection attempt. 
    /// Used if a <see cref="SqlBase.ConnectionString"/> is not specified.</para>
    /// <para><i>CommandTimeout</i></para>
    /// <para>Number of seconds to wait before failing the kill request. </para>
    /// <para><b>WARNING: This action will attempt to kill all processes acting on the 
    /// specified table. This may include DTS and replication queries as well 
    /// as any active users.</b></para>
    /// <para><b>This task has not be tested against Yukon and may have unexpected behaviour.</b></para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///         <Sql.DisconnectUsers
    ///             ServerName="(local)"
    ///             DatabaseName="testDB"
    ///             CommandTimeout="60" />
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    public class DisconnectUsers : SqlBase
    {
        private string databaseName = String.Empty;

        /// <summary>
        /// Initializes a new instance of the DisconnectUsers class.
        /// </summary>
        public DisconnectUsers()
        {
        }

        /// <summary>
        /// Performs the action of this task.
        /// </summary>
        protected override void InternalExecute()
        {
            #region Check Parameters
            if (this.ConnectionString.Length == 0)
            {
                throw (new ApplicationException("No connection information set."));
            }
            #endregion

            #region Execute code
            int numUsers = SdcSql.Database.DisconnectUserProcessesWithConnectionString(
                this.ConnectionString, this.databaseName, this.CommandTimeout
                );
            Console.WriteLine("users killed = " + numUsers.ToString(CultureInfo.InvariantCulture));
            Log.LogMessageFromResources("Sql.DisconnectUsers", numUsers, this.databaseName);
            #endregion
        }


        /// <summary>
        /// Database to perform the action on
        /// </summary>
        /// <value>A valid database name</value>
        [Required]
        public string DatabaseName
        {
            get
            {
                return (databaseName == null ? String.Empty : databaseName);
            }
            set
            {
                switch (value.ToLower())
                {
                    case "master":
                    case "model":
                    case "msdb":
                    case "tempdb":
                        string errorText = string.Format(
                            CultureInfo.InvariantCulture,
                            "Cannot disconnect users from \"{0}\" table, as this is a known system table.",
                            value);
                        throw new ApplicationException(errorText);
                    default:
                        databaseName = value;
                        break;
                }
            }
        }
    }
}
